﻿using Sasc.PV.Common;
using Sasc.PV.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sasc.PV.BLL
{
    public abstract class CheJianManagementBase<TCheJianGongXuTarget> : ICheJianManagement<TCheJianGongXuTarget>
        where TCheJianGongXuTarget : class, ICheJianGongXuTarget, new()
    {
        #region Ctor
        public CheJianManagementBase()
        {
            CheJianName = CheJianUtils.GetCheJianName(this.GetType());
        }
        #endregion

        #region Properties
        public string CheJianName { get; private set; }
        protected string LoginUserName { get { return PublicMethod.GetSessionValue("UserName"); } }
        #endregion

        #region WriteRiZhi
        protected void WriteRiZhi(string logContent)
        {
            //写系统日志
            ERPRiZhi MyRiZhi = new ERPRiZhi();
            MyRiZhi.UserName = LoginUserName;
            MyRiZhi.DoSomething = logContent;
            MyRiZhi.IpStr = Utils.GetIPAddress();
            MyRiZhi.Add();
        }
        #endregion

        #region GetCheJianRecTableName
        public string GetCheJianRecTableName()
        {
            return (string)(DbHelperSQL.GetSingle(string.Format("SELECT GongXuRecTable FROM PvcCheJian WHERE Name='{0}'", CheJianName)) ?? default(string));
        }
        #endregion

        #region AddGongXuRec
        public virtual IPvGongXuRecModel AddGongXuRec<TCheJian>(CheJianGongXuBase<TCheJian, TCheJianGongXuTarget> gongxu, TCheJianGongXuTarget target)
                                         where TCheJian : CheJianManagementBase<TCheJianGongXuTarget>, new()
        {
            var gongXuRec = CreateGongXuRecModel<TCheJian>(gongxu, target);
            gongXuRec.ID = gongXuRec.Add();
            return gongXuRec;
        }
        #endregion

        #region AddGongXuRec
        public virtual bool DeleteGongXuRecList(string idWhereSql)
        {
            var deleteGongXuRecSqlBuilder = new StringBuilder();
            deleteGongXuRecSqlBuilder.AppendFormat("DELETE FROM {0} WHERE ID IN ({1})", GetCheJianRecTableName(), idWhereSql);
            DbHelperSQL.ExecuteSql(deleteGongXuRecSqlBuilder.ToString());

            return true;
        }
        #endregion

        #region CreateGongXuRecModel
        protected abstract IPvGongXuRecModel CreateGongXuRecModel<TCheJian>(CheJianGongXuBase<TCheJian, TCheJianGongXuTarget> gongxu, TCheJianGongXuTarget target)
            where TCheJian : CheJianManagementBase<TCheJianGongXuTarget>, new();
        #endregion

        #region CanProcess
        public virtual bool CanProcess<TCheJian>(CheJianGongXuBase<TCheJian, TCheJianGongXuTarget> gongxu, IPvGongXuModel gongXuModel, TCheJianGongXuTarget target, out string reason)
            where TCheJian : CheJianManagementBase<TCheJianGongXuTarget>, new()
        {
            reason = string.Empty;

            if (!ExistsGongXuTarget(target, out reason))
                return false;

            var dependGongXu = CreateDependGongXu(gongxu)as CheJianGongXuBase<TCheJian, TCheJianGongXuTarget>;
            if (dependGongXu != null)
            {
                var hasProcessedDependGongXu = HasBeenProcessed(dependGongXu, target);
                if (!hasProcessedDependGongXu)
                {
                    reason = string.Format("{1} 还未经过工序:{0} 处理，请重新选择。", gongxu.GongXuName, target.ToString());
                    return false;
                }
            }

            var hasBeenProcessed = HasBeenProcessed(gongxu, target);

            if (hasBeenProcessed)
                reason = string.Format("已经{1}处理过:{0}，请重新选择。", target.ToString(), gongxu.GongXuName);
            return !hasBeenProcessed;
        }

        public bool HasBeenProcessed<TCheJian>(CheJianGongXuBase<TCheJian, TCheJianGongXuTarget> gongXu,  TCheJianGongXuTarget target)
            where TCheJian : CheJianManagementBase<TCheJianGongXuTarget>, new()
        {
            var whereSQLBuilder = new StringBuilder();
            whereSQLBuilder.Append(target.GenerateExistWhereSQL());

            var otherExistWhereSQL = GenerateOtherCommonExistWhereSQL(gongXu, target);
            if (!string.IsNullOrEmpty(otherExistWhereSQL))
            {
                if (whereSQLBuilder.Length > 0)
                    whereSQLBuilder.Append(" AND ");
                whereSQLBuilder.Append(otherExistWhereSQL);
            }
            if (whereSQLBuilder.Length > 0)
                whereSQLBuilder.Insert(0, " AND ");

            var sqlBuilder = new StringBuilder();
            sqlBuilder.AppendFormat("SELECT 1 FROM {0} WHERE 1=1 {1}", gongXu.GetGongXuDbTableName(), whereSQLBuilder.ToString());
            return (int)(DbHelperSQL.GetSingle(sqlBuilder.ToString()) ?? 0) == 1;            
        }

        protected abstract bool ExistsGongXuTarget(TCheJianGongXuTarget target, out string reason);

        /// <summary>
        /// 一般是返工条件
        /// </summary>
        /// <typeparam name="TCheJian"></typeparam>
        /// <param name="gongxu"></param>
        /// <param name="gongXuModel"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        protected virtual string GenerateOtherCommonExistWhereSQL<TCheJian>(CheJianGongXuBase<TCheJian, TCheJianGongXuTarget> gongxu, TCheJianGongXuTarget target)
                        where TCheJian : CheJianManagementBase<TCheJianGongXuTarget>, new()
        {
            return string.Empty;
        }
        #endregion

        #region 获取依赖工序
        public ICheJianGongXu CreateDependGongXu(ICheJianGongXu gongXu)
        {
            var dependGongXuName = GetDependGongXu(gongXu);
            if (!string.IsNullOrEmpty(dependGongXuName))
            {
                try
                {
                    var dependGongXuType = CheJianUtils.GetCheJianGongXuType(CheJianName, dependGongXuName);
                    return Activator.CreateInstance(dependGongXuType) as ICheJianGongXu;
                }
                catch
                { 
                }
            }

            return default(ICheJianGongXu);
        }
        public string GetDependGongXu(ICheJianGongXu gongXu)
        {
            var sqlBuilder = new StringBuilder();
            sqlBuilder.AppendFormat("SELECT Name FROM PvcGongXu WHERE ID IN(SELECT DependOnGongXuID FROM PvcGongXu WHERE Name='{0}' AND CheJianName='{1}')", gongXu.GongXuName, CheJianName);
            return (string)(DbHelperSQL.GetSingle(sqlBuilder.ToString()) ?? default(string));
        }
        #endregion
    }
}
